package cmlabs.simpleciphers;

import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: jte
 * Date: 9.4.11
 * Time: 20.15
 * To change this template use File | Settings | File Templates.
 */
public class VizhinerCipher {

    public VizhinerCipher(int T) {

        if (T < 1 || T > 65536) {
            throw new IllegalArgumentException("Incorrect length of period");
        }
        Random generator = new Random(System.currentTimeMillis());
        this.T = T;
        key = new int[T];
        for (int i = 0; i < key.length; ++i) {
            key[i] = generator.nextInt(T);
        }
    }

    public String encrypt(String value) {
        char[] characters = value.toCharArray();
        for (int i = 0; i < characters.length; ++i) {
            characters[i] = (char) (((int) characters[i] + key[i % T]) % T);
        }
        return new String(characters);
    }

    public String decrypt(String value) {
        char[] characters = value.toCharArray();
        for (int i = 0; i < characters.length; ++i) {
            characters[i] = (char) (((int) characters[i] + T - key[i % T]) % T);
        }
        return new String(characters);

    }

    private int[] key;
    private int T;
}
